package com.matt.controller.api.controller;

import com.dotflat.util.excelUtil.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonArray;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.model.StatusResponse;
import com.matt.controller.api.domin.Thermometer;
import com.matt.controller.api.domin.ThermometerRequest;
import com.matt.controller.api.domin.ThermometerRequestAll;
import com.matt.controller.api.service.ThermometerService;
import com.matt.domain.api.HlThermometerDevice;
import com.matt.foundation.constant.PermissionConstant;
import com.matt.foundation.constant.RequestConstant;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.HttpClientUtil;
import com.matt.foundation.utils.annotation.RequiredPermissions;
import com.matt.repository.ThermometerRepository;
import com.matt.repository.api.HIThermometerDeviceRepository;
import com.tuo51.components.redis.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

import static com.matt.foundation.constant.PermissionConstant.TEACH_STAFF_EDIT;


@RestController
@RequestMapping("/api/thermometer")
@Slf4j
@Api(tags = "获取硬件接口数据")
public class ThermometerController {

    @Autowired
    ThermometerRepository thermometerRepository;

    @Autowired
    HIThermometerDeviceRepository  hiThermometerDeviceRepository;

    @Autowired
    private MemVerificationCache cache;

    @Autowired
    private RedisService redisService;
    @Value("${server.gov.url}")
    private  String govUrl;

    @RequiredPermissions(PermissionConstant.API_Thermometer1)
    @ApiOperation("获取最新的温度数据")
    @RequestMapping(value = "/getThermometer", method = RequestMethod.GET)
    public StatusResponse getThermometer(@RequestHeader(RequestConstant.TICKET) String ticket,Long deviceId) {
        try {
            StaffDTO staff = cache.getStaff(ticket);
            String areaId = staff.getAreaId();

            Thermometer thermometer;
            if("0c80a4b8593d46b4bc712fc3be08056e".equals(areaId)){
                 thermometer = thermometerRepository.findAllByLimitThermometer(areaId);
            }else {
                thermometer = thermometerRepository.findAllByLimitThermometer1(areaId,deviceId);
            }

            return StatusResponse.success(thermometer);
        }catch (Exception e) {
            e.printStackTrace();
            return StatusResponse.error("数据解析失败: ",e.getMessage());
        }

    }



    @RequiredPermissions(PermissionConstant.API_Thermometer)
    @RequestMapping(value = "/getAllThermometer", method = RequestMethod.POST)
    public StatusResponse getAllThermometer1(@RequestBody String json){
        try {
//            ObjectMapper objectMapper = new ObjectMapper();
//            ThermometerRequest request = objectMapper.readValue(json, ThermometerRequest.class);
//            Thermometer thermometer=new Thermometer();
//            thermometer.setHumidity(request.getHumidity());
//            thermometer.setPm2_5(request.getPm2_5());
//            thermometer.setCreateTime(LocalDateTime.now());
//            thermometer.setTemperature(request.getTemperature());
//            //强制给长沙的
//            thermometer.setAreaId("0c80a4b8593d46b4bc712fc3be08056e");
//            // 处理接收到的数据
//            System.out.println("收到数据: "+ request.toString());
//            thermometer.setThermometerData(request.toString());
//            thermometerRepository.save(thermometer);

            ObjectMapper objectMapper = new ObjectMapper();
            ThermometerRequest request = objectMapper.readValue(json, ThermometerRequest.class);
            Thermometer thermometer = new Thermometer();
            thermometer.setHumidity(request.getHumidity());
            thermometer.setPm2_5(request.getPm2_5());
            thermometer.setCreateTime(LocalDateTime.now());
            thermometer.setTemperature(request.getTemperature());
            //强制给长沙的
            thermometer.setAreaId("0c80a4b8593d46b4bc712fc3be08056e");
            // 处理接收到的数据
            System.out.println("收到数据: "+ request.toString());
            thermometer.setThermometerData(request.toString());
            thermometerRepository.save(thermometer);

            // 构造参数并发送GET请求（独立处理异常，不影响主流程）
//            sendGetRequest(request);

            return StatusResponse.success("数据接收成功+++++++++++");

        }catch (Exception e) {
            e.printStackTrace();
            return StatusResponse.error("数据解析失败: ",e.getMessage());
        }

    }

    private void sendGetRequest(ThermometerRequest request) {
        try {
            String temperature = URLEncoder.encode(String.valueOf(request.getTemperature()), "UTF-8");
            String humidity = URLEncoder.encode(String.valueOf(request.getHumidity()), "UTF-8");
            String pm25 = URLEncoder.encode(String.valueOf(request.getPm2_5()), "UTF-8");
            String areaId = URLEncoder.encode("0c80a4b8593d46b4bc712fc3be08056e", "UTF-8");
            String areaName = URLEncoder.encode("长沙市雨花区托育综合服务中心", "UTF-8");
            String district = URLEncoder.encode("雨花区", "UTF-8");
            String formaldehyde = URLEncoder.encode("0.08", "UTF-8");
            String airQuality = URLEncoder.encode("0", "UTF-8");

            String query = "temperature=" + temperature +
                    "&humidity=" + humidity +
                    "&pm2_5=" + pm25 +
                    "&institutionName=" + areaName +
                    "&district=" + district +
                    "&formaldehyde=" + formaldehyde +
                    "&airQuality=" + airQuality +
                    "&areaId=" + areaId;

            String url = govUrl + "/api/records/add?" + query;

//            HttpClientUtil.sendGet(url);
        } catch (Exception e) {
            // 记录错误但不抛出异常，确保主流程继续执行
            log.error("发送GET请求失败: {}", e.getMessage(), e);
        }
    }

    @RequiredPermissions(PermissionConstant.API_Thermometer1)
    @RequestMapping(value = "/getAllThermometer/{id}", method = RequestMethod.POST)
    public StatusResponse getAllThermometerWithId(@PathVariable Long id, @RequestBody String json){
        try {
            // 1. 解析请求数据并保存到数据库
            ObjectMapper objectMapper = new ObjectMapper();
//            ThermometerRequest request = objectMapper.readValue(json, ThermometerRequest.class);
            ThermometerRequestAll request = objectMapper.readValue(json, ThermometerRequestAll.class);
            Thermometer thermometer = new Thermometer();
            thermometer.setHumidity(request.getHumidity());
            thermometer.setPm2_5(request.getPm2_5());
            thermometer.setCreateTime(LocalDateTime.now());
            thermometer.setTemperature(request.getTemperature());
            thermometer.setHcho(request.getHcho());
            thermometer.setCo2(request.getCo2());
            // 2. 获取设备对应的areaId
            HlThermometerDevice areaIdById1 = hiThermometerDeviceRepository.findAreaIdById1(String.valueOf(id));
            if (areaIdById1==null) {
                return StatusResponse.error("请添加设备和设备对应的园区", "设备id为" + id);
            }
            thermometer.setDeviceId(id);
            thermometer.setDeviceName(areaIdById1.getName());
            thermometer.setAreaId(areaIdById1.getAreaId());

            // 3. 保存数据到数据库
            thermometer.setThermometerData(request.toString());
            System.out.println("收到数据为============="+request.toString());
            // 3. 将Thermometer对象序列化为JSON字符串，存入Redis列表
//            String redisKey = "thermometer:data:" + id; // 按设备ID隔离：thermometer:data:1001
//            String thermometerJson = objectMapper.writeValueAsString(thermometer); // 转为JSON字符串
//            redisService.pushFromTail(redisKey, thermometerJson); // 从列表尾部插入
//
//            // 4. 可选：设置RedisKey过期时间（如24小时，避免内存溢出）
//            redisService.refreshTime(redisKey, 24 * 60 * 60); // 24小时过期
//
//            return StatusResponse.success("数据暂存成功，设备id: " + id);
            thermometerRepository.save(thermometer);

            // 4. 发送GET请求（独立处理异常，不影响主流程）
//            sendGetRequest(request, areaId, id);

            // 5. 返回成功响应（即使发送失败也返回成功）
            return StatusResponse.success("数据接收成功==========设备id为: " + id);
        } catch (JsonProcessingException e) {
            // 处理JSON解析异常
            return StatusResponse.error("数据解析失败: ", e.getMessage());
        } catch (Exception e) {
            // 捕获其他未知异常
            e.printStackTrace();
            return StatusResponse.error("系统异常: ", e.getMessage());
        }
    }

    @RequiredPermissions(PermissionConstant.API_Thermometer)
    @RequestMapping(value = "/getAllThermometers", method = RequestMethod.POST)
    public StatusResponse getAllThermometer2(@RequestBody String json){
        try {

            ObjectMapper objectMapper = new ObjectMapper();
            ThermometerRequestAll request = objectMapper.readValue(json, ThermometerRequestAll.class);
//            Thermometer thermometer = new Thermometer();
//            thermometer.setHumidity(request.getHumidity());
//            thermometer.setPm2_5(request.getPm2_5());
//            thermometer.setCreateTime(LocalDateTime.now());
//            thermometer.setTemperature(request.getTemperature());
//            //强制给长沙的
//            thermometer.setAreaId("0c80a4b8593d46b4bc712fc3be08056e");
            // 处理接收到的数据
            System.out.println("收到数据: "+ request.toString());
//            thermometer.setThermometerData(request.toString());
//            thermometerRepository.save(thermometer);

            // 构造参数并发送GET请求（独立处理异常，不影响主流程）
//            sendGetRequest(request);

            return StatusResponse.success("数据接收成功+++++++++++");

        }catch (Exception e) {
            e.printStackTrace();
            return StatusResponse.error("数据解析失败: ",e.getMessage());
        }

    }

    @RequiredPermissions(PermissionConstant.API_Thermometer1)
    @RequestMapping(value = "/getAllThermometers/{id}", method = RequestMethod.POST)
    public StatusResponse getAllThermometerWithIds(@PathVariable Long id, @RequestBody String json){
        try {
            // 1. 解析请求数据并保存到数据库
            ObjectMapper objectMapper = new ObjectMapper();
            ThermometerRequestAll request = objectMapper.readValue(json, ThermometerRequestAll.class);
            Thermometer thermometer = new Thermometer();
            thermometer.setHumidity(request.getHumidity());
            thermometer.setPm2_5(request.getPm2_5());
            thermometer.setCreateTime(LocalDateTime.now());
            thermometer.setTemperature(request.getTemperature());

            // 2. 获取设备对应的areaId
            String areaId = hiThermometerDeviceRepository.findAreaIdById(String.valueOf(id));
            if (StringUtils.isEmpty(areaId)) {
                return StatusResponse.error("请添加设备和设备对应的园区", "设备id为" + id);
            }
            thermometer.setDeviceId(id);
            thermometer.setAreaId(areaId);

            // 3. 保存数据到数据库
            thermometer.setThermometerData(request.toString());
            thermometerRepository.save(thermometer);

            // 4. 发送GET请求（独立处理异常，不影响主流程）
//            sendGetRequest(request, areaId, id);

            // 5. 返回成功响应（即使发送失败也返回成功）
            return StatusResponse.success("数据接收成功==========设备id为: " + id);
        } catch (JsonProcessingException e) {
            // 处理JSON解析异常
            return StatusResponse.error("数据解析失败: ", e.getMessage());
        } catch (Exception e) {
            // 捕获其他未知异常
            e.printStackTrace();
            return StatusResponse.error("系统异常: ", e.getMessage());
        }
    }

    // 独立方法发送GET请求，异常不影响主流程
    private void sendGetRequest(ThermometerRequest request, String areaId, Long deviceId) {
        try {
            // 参数编码
            String temperature = URLEncoder.encode(String.valueOf(request.getTemperature()), "UTF-8");
            String humidity = URLEncoder.encode(String.valueOf(request.getHumidity()), "UTF-8");
            String pm25 = URLEncoder.encode(String.valueOf(request.getPm2_5()), "UTF-8");
            String encodedAreaId = URLEncoder.encode(areaId, "UTF-8");
            String areaName = URLEncoder.encode("广西工商技师学院实验幼儿园", "UTF-8");
            String district = URLEncoder.encode("梧州市", "UTF-8");
            String formaldehyde = URLEncoder.encode("0.08", "UTF-8");
            String airQuality = URLEncoder.encode("0", "UTF-8");

            // 构造请求URL
            String query = "temperature=" + temperature +
                    "&humidity=" + humidity +
                    "&pm2_5=" + pm25 +
                    "&institutionName=" + areaName +
                    "&district=" + district +
                    "&formaldehyde=" + formaldehyde +
                    "&airQuality=" + airQuality +
                    "&areaId=" + encodedAreaId;

            String url = govUrl + "/api/records/add?" + query;

            // 发送请求并捕获异常
            HttpClientUtil.sendGet(url);
            log.info("成功发送GET请求到政府接口，设备ID: {}", deviceId);
        } catch (Exception e) {
            // 记录错误但不抛出异常，确保主流程继续执行
            log.error("发送GET请求到政府接口失败，设备ID: {}. 错误信息: {}", deviceId, e.getMessage(), e);
        }
    }
}
